<?php

namespace app\api\controller\datas;

use think\Config;
use think\Db;

/**
 * 余额
 * Class Balance
 * @package app\api\controller\datas
 */
class Balance
{

	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config = [
		"prefix" 		=> "fd_",
		"banc"			=> "balance",
		"typs"			=> "balance_type",
		"logs" 			=> "balance_log"
	];

	/**
	 * BalanceType模型对象
	 * @var \app\common\model\BalanceType
	 */
	protected $typeModel = null;

	/**
	 * 默认架构方法
	 */
	public function __construct()
	{
		$this->typeModel = new \app\common\model\BalanceType;
	}

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 账户余额
	 */
	public function get_totals($uid)
	{
		return \app\common\controller\Balance::instance()->get($uid);
	}

	/**
	 * 账户明细
	 */
	public function get_details($uid)
	{
		if (!$uid) {
			return false;
		}
		$where = "main_id = {$uid}";
		$list = Db::name($this->config['logs'])
			->where($where)
			->field("id,balance_type typs,change_state isChg,money,before,after,mome")
			->select();
		if ($list) {
			$arr = $this->typeModel->column("nick", "code");
			foreach ($list as $key => $v) {
				$list[$key]['typeNick'] = $arr[$v["typs"]];
				$list[$key]['chgeNick'] = $v["isChg"] == 1 ? '收入' : '支出';
			}
		}
		return $list;
	}

	/**
	 * 商家
	 */
	public function marchent_earn($uid)
	{
		$ret = [
			"totals" => '0.00',
			"currents" => '0.00',
			'lasts' => '0.00'
		];
		if ($uid) {
			$where = "";
			$ret["totals"] = $this->get_totals($uid);
			$times = date("Ym", time());
			$where = "main_id = {$uid} and change_state = 1 and from_unixtime(times , '%Y%m') = '{$times}'";
			$ret["currents"] = Db::name($this->config['logs'])->where($where)->sum("money");

			$lastTime = date("Ym",strtotime("-1 month", time()));
			$where = "main_id = {$uid} and change_state = 1 and from_unixtime(times , '%Y%m') = '{$lastTime}'";
			
			$ret["lasts"] = Db::name($this->config['logs'])->where($where)->sum("money");
		}
		return $ret;
	}
}
